package command

import (
	"github.com/kardianos/service"
	"log"
	"proxy_resource_test/config"
	"proxy_resource_test/internal/app"
)

// Handle 根据命令行参数控制服务安装、启动、停止
// Handle 根据命令行参数控制服务安装、启动、停止
type serviceAdapter struct {
	svc app.App
}

// Start 实现 service.Interface
func (a *serviceAdapter) Start(s service.Service) error {
	return a.svc.Run()
}

// Stop 实现 service.Interface
func (a *serviceAdapter) Stop(s service.Service) error {
	return a.svc.Stop()
}

func Handle(svcApp app.App, args []string) error {
	svcConfig := &service.Config{
		Name:        config.AppConfig.Name,
		DisplayName: config.AppConfig.Name,
		Description: config.AppConfig.Name,
		Option: map[string]interface{}{
			"LimitNOFILE": 1000000,
		},
	}
	adapter := &serviceAdapter{svc: svcApp}
	svc, err := service.New(adapter, svcConfig)
	if err != nil {
		return err
	}

	switch args[0] {
	case "install":
		return svc.Install()
	case "uninstall":
		return svc.Uninstall()
	case "start":
		return svc.Start()
	case "stop":
		return svc.Stop()
	case "restart":
		return svc.Restart()
	case "status":
		sta, err := svc.Status()
		if err != nil {
			return err
		}
		var status = "StatusUnknown"
		if sta == service.StatusRunning {
			status = "Running"
		} else if sta == service.StatusStopped {
			status = "Stopped"
		}
		log.Printf("Service status: %v", status)
		return nil
	default:
		log.Printf("unknown command: %s", args[0])
	}
	return nil
}
